package com.travel.commons.utils;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.travel.commons.filter.SQLFilter;
import org.apache.commons.lang.StringUtils;
import org.springframework.util.ObjectUtils;

import java.util.Map;

/**
 * 查询参数
 *
 * @author pengrui.r@qq.com
 */
public class Query<T> {
    public IPage<T> getPage(Map<String, Object> params) {
        return  this.getPage(params, null, false);
    }

    public IPage<T> getPage(Map<String, Object> params, String defaultOrderField, boolean isAsc) {
        long currPage = 1;
        long limit = 10;

        if (!ObjectUtils.isEmpty(params.get(Constant.PAGE))) {
            currPage = ((Integer) params.get(Constant.PAGE)).longValue();
        }
        if (!ObjectUtils.isEmpty(params.get(Constant.LIMIT))) {
            limit = ((Integer) params.get(Constant.LIMIT)).longValue();
        }

        Page<T> page = new Page<>(currPage, limit);
        params.put(Constant.PAGE, page);

        String orderField = SQLFilter.sqlInject((String) params.get(Constant.ORDER_FIELD));
        String order = (String) params.get(Constant.ORDER);

        if (StringUtils.isNotEmpty(orderField) && StringUtils.isNotEmpty(order)) {
            if (Constant.ASC.equalsIgnoreCase(order)) {
                return page.addOrder(OrderItem.asc(orderField));
            } else {
                return page.addOrder(OrderItem.desc(orderField));
            }
        }

        if (StringUtils.isBlank(defaultOrderField)) {
            return page;
        }

        if (isAsc) {
            page.addOrder(OrderItem.asc(orderField));
        } else {
            page.addOrder(OrderItem.desc(orderField));
        }
        return page;
    }
}
